package com.zly.framework.rbac.utils;

import com.zly.framework.rbac.configuration.SysAuthConfiguration;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class JwtUtils {
    @Resource
    private SysAuthConfiguration sysAuthConfiguration;
    public String generateToken(String username,  Collection<GrantedAuthority> permissionList) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * 60 * 60 * 24 * sysAuthConfiguration.getJwt().getExpire());
        List<Object> permissions = new ArrayList<>();
        if (permissionList!=null){
            for (GrantedAuthority grantedAuthority : permissionList) {
                permissions.add(grantedAuthority.getAuthority());
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("permissions", permissions);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .addClaims(map)
                .setExpiration(expireDate)    // 7天过期
                .signWith(SignatureAlgorithm.HS512, sysAuthConfiguration.getJwt().getSecret())
                .compact();
    }

    // 解析JWT
    public Claims getClaimsByToken(String jwt) {
        return Jwts.parser()
                .setSigningKey( sysAuthConfiguration.getJwt().getSecret())
                .parseClaimsJws(jwt)
                .getBody();

    }

    // 解析JWT 获取用户名
    public String getUsername(String jwt) {
        return (String) Jwts.parser()
                .setSigningKey( sysAuthConfiguration.getJwt().getSecret())
                .parseClaimsJws(jwt)
                .getBody().get("sub");

    }

    // 解析JWT 获取用户权限
    public List<String> getPermission(String jwt) {
        return (List<String>) Jwts.parser()
                .setSigningKey( sysAuthConfiguration.getJwt().getSecret())
                .parseClaimsJws(jwt)
                .getBody().get("permissions");

    }

    // 判断JWT是否过期
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
